package javbot.gui;

import java.awt.BorderLayout;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.event.ItemEvent;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;

public class PosPanel extends JPanel {

	private static final long serialVersionUID = -5374324478151458353L;
	private JLabel jLabel = null;
	private JToggleButton jToggleButton = null;
	private boolean grab = false;
	private ScriptPanel scriptPanel;
	
	private final class PosThread extends Thread {
		public void run() {
			
			Point point = MouseInfo.getPointerInfo().getLocation();
			Point pointOld;
			int staticCount = 0;
			
			// Infinite loop run while posPanel is active
			while (true) {
				
				pointOld = point;
				point = MouseInfo.getPointerInfo().getLocation();
		
				if (grab && point.equals(pointOld)) {
					
					staticCount++;
					
					if (staticCount == 10) {
						jToggleButton.doClick();
						scriptPanel.insertPoint(point);
						staticCount = 0;
						
					}
					
				} else {
					staticCount = 0;
				}
				
				jLabel.setText("(" + (int) point.getX() + ", " + (int) point.getY() + ")");
				
				try {
					sleep(100);
				} catch (InterruptedException e) {
					System.out.println(e);
					break;
				}
		
			}
		}
	}
	
	/**
	 * This is the default constructor
	 */
	public PosPanel(ScriptPanel sp) {
		super();
		initialize();
		this.scriptPanel = sp;
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		jLabel = new JLabel();
		this.setLayout(new BorderLayout());
		this.setSize(95, 61);
		this.add(jLabel, java.awt.BorderLayout.CENTER);
		this.add(getJToggleButton(), java.awt.BorderLayout.EAST);
		(new PosThread()).start();
	}

	/**
	 * This method initializes jToggleButton	
	 * 	
	 * @return javax.swing.JToggleButton	
	 */
	private JToggleButton getJToggleButton() {
		if (jToggleButton == null) {
			jToggleButton = new JToggleButton();
			jToggleButton.setText("Grab");
			jToggleButton.addItemListener(new java.awt.event.ItemListener() {
				public void itemStateChanged(java.awt.event.ItemEvent e) {
					
					if (e.getStateChange() == ItemEvent.SELECTED) {
						grab = true;
						String selectedText = scriptPanel.scriptInput.getSelectedText();
						if (selectedText != null && selectedText.length() > 0) {
							scriptPanel.scriptInput.replaceSelection("");
						}
					} else {
						grab = false;
					}
				}
			});

		}
		return jToggleButton;
	}

	public void setEnabled(boolean enabled) {
		super.setEnabled(enabled);
		jToggleButton.setEnabled(enabled);
	}

}  //  @jve:decl-index=0:visual-constraint="10,10"
